﻿using System;
using System.Data.Entity;
using System.Web.Mvc;
using Gluten.Models;
using System.Web.Security;
using System.Web;
using System.Net.Mail;
using PagedList;

namespace Gluten.Controllers
{
    public class HomeController : Controller
    {
        private DBManager db = new DBManager();

        public ActionResult Index(int? page)
        {            
            Database.SetInitializer<DataBaseContext>(
                new DropCreateDatabaseIfModelChanges<DataBaseContext>());
            ViewBag.Label = db.GetNearLabel(Guid.Empty);
            var sheetNumber = page ?? 1;
            ViewBag.Pages = db.GetAllPages(false).ToPagedList(sheetNumber, 9);
            ViewBag.MainMenu = db.GetAllMainMenu();
            ViewBag.Menu = db.GetMenu(Guid.Empty) ?? new Menu();
            ViewBag.pagedUrl = "index";
            return View();
        }

        [HttpGet]
        public ActionResult Page(Guid id)
        {
            var page = db.GetPage(id);
            ViewBag.Label = db.GetNearLabel(page.MenuParent);
            ViewBag.MainMenu = db.GetAllMainMenu();
            return View(page);
        }

        [HttpGet]
        public ActionResult Menu(Guid id, int? page)
        {
            var sheetNumber = page ?? 1;
            ViewBag.Pages = db.GetAllPagesByMenu(id, false).ToPagedList(sheetNumber, 9);
            ViewBag.MainMenu = db.GetAllMainMenu();
            ViewBag.Submenu = db.GetAllSubmenu(id);
            var menu = db.GetMenu(id);
            ViewBag.Menu = menu;
            ViewBag.pagedUrl = "menu/" + id;
            ViewBag.Label = db.GetNearLabel(menu.Id);
            return View();
        }

        public ActionResult writeToAdmin()
        {
            ViewBag.Label = db.GetLabel(Guid.Empty);
            ViewBag.MainMenu = db.GetAllMainMenu();
            return View();
        }

        [HttpPost]
        public void writeToAdmin(Mail mail)
        {

            var admin = Membership.GetUser("admin");
            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            smtp.Credentials = new System.Net.NetworkCredential("chakmidlot@gmail.com",",jkmit10Cbvdjkjaa");
            smtp.EnableSsl = true;
            var mailForAdmin = new MailMessage(
                    mail.from,
                    admin.Email,
                    mail.Title,
                    mail.Body);
            smtp.Send(mailForAdmin);
            Response.Redirect(Url.Action("index"));
        }

        public void CreteUser()
        {
            Membership.DeleteUser("admin");
            Membership.CreateUser("admin", "admin123", "chakmidlot@gmail.com");
            Roles.AddUserToRole("admin", "admin");
            Response.Redirect(Url.Action("index"));
        }

    }
}
